#!/usr/bin/env python3
"""
工具基类定义
"""

import json
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional, List
from datetime import datetime
from dataclasses import dataclass

@dataclass
class ToolResult:
    """工具执行结果"""
    success: bool
    data: Any = None
    error: str = None
    execution_time: float = 0.0
    metadata: Dict[str, Any] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "success": self.success,
            "data": self.data,
            "error": self.error,
            "execution_time": self.execution_time,
            "metadata": self.metadata or {}
        }

class Tool(ABC):
    """工具基类"""
    
    def __init__(self, name: str, description: str, version: str = "1.0.0"):
        self.name = name
        self.description = description
        self.version = version
        self.created_at = datetime.now()
        self.last_used = None
        self.usage_count = 0
    
    @abstractmethod
    def execute(self, **kwargs) -> ToolResult:
        """执行工具"""
        pass
    
    @abstractmethod
    def get_schema(self) -> Dict[str, Any]:
        """获取工具调用模式"""
        pass
    
    def validate_parameters(self, parameters: Dict[str, Any]) -> bool:
        """验证参数"""
        schema = self.get_schema()
        required_params = schema.get("required", [])
        
        # 检查必需参数
        for param in required_params:
            if param not in parameters:
                return False
        
        return True
    
    def get_parameter_schema(self) -> Dict[str, Any]:
        """获取参数模式"""
        schema = self.get_schema()
        return schema.get("parameters", {})
    
    def update_usage(self):
        """更新使用统计"""
        self.usage_count += 1
        self.last_used = datetime.now()
    
    def get_info(self) -> Dict[str, Any]:
        """获取工具信息"""
        return {
            "name": self.name,
            "description": self.description,
            "version": self.version,
            "created_at": self.created_at.isoformat(),
            "last_used": self.last_used.isoformat() if self.last_used else None,
            "usage_count": self.usage_count,
            "schema": self.get_schema()
        }
